
package com.mol.market.ui_v4;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.*;
import android.widget.*;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.ApiResponse;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.StringUtils;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.common.vo.TagsInfo;
import com.mol.market.common.widget.CategoryTagView;
import com.mol.market.demo.ui.ThirdFragmentActivity;
import com.mol.market.demo.widget.BaseFragmentActivity;
import com.mol.market.ui.ScreenshotActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 产品详细信息Fragment。
 *
 * Author: Andrew.Wang
 * Date  : 12-12-20
 */
public class ProductDetailFragment extends SherlockFragment
        implements View.OnClickListener, CategoryTagView.TagViewListener,
                    LoaderManager.LoaderCallbacks<ApiResponse> {

    private static final int MORE_PRODUCT_ID = 100;

    private ProductDetail mProductDetail;

    private boolean isInit;

    private SherlockFragmentActivity mActivity;

    /**
     * 产品描述信息的状态（长描述/短描述）
     */
    private boolean mIsShortDescription = true;

    /**
     * 产品短描述信息文本
     */
    private TextView mShortDescription;

    /**
     * 产品长描述信息文本
     */
    private TextView mLongDescription;

    /**
     * 展示更多产品描述信息按钮
     */
    private Button mMoreButton;

    private ArrayList<HashMap<String, Object>> mMoreApps;

    private boolean mIsLoaded;

    private LinearLayout mGalleryBackground;

    private Session mSession;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(false);
        mActivity = getSherlockActivity();
        mSession = Session.get(mActivity);
        mProductDetail = (ProductDetail) getArguments().getSerializable(Constants.EXTRA_PRDUCT_DETAIL);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mProductDetail = null;
        mActivity = null;
        mShortDescription = null;
        mLongDescription = null;
        mMoreButton = null;
        mMoreApps = null;
        recycleImage();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_product_detail, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!mIsLoaded) {
            initViews(mProductDetail);
        }
        if (mProductDetail != null) {
            final LoaderManager loaderManager = getLoaderManager();
            loaderManager.initLoader(MarketAPI.ACTION_GET_RECOMMEND_BY_APP, null, this);
            loaderManager.initLoader(MarketAPI.ACTION_GET_TAGS_IN_DETAILS, null, this);
            loaderManager.initLoader(MarketAPI.ACTION_GET_MYRATING, null, this);
        }
    }

    public void initViews(ProductDetail product) {
        mProductDetail = product;
        initGallery(mProductDetail);
        initProductInfo(mProductDetail);
        initDescriptionView(mProductDetail);
        initRatingView();
        mIsLoaded = true;
    }

    /**
     * 初始化应用截图Gallery
     */
    private void initGallery(ProductDetail product) {

        ArrayList<String> mUrls = new ArrayList<String>();
        String[] screenUrl = product.getScreenshotLdpi();
        for (String url : screenUrl) {
            if (TextUtils.isEmpty(url)) {
                continue;
            }
            mUrls.add(url);
        }
        if (mUrls.size() > 0) {

            LayoutInflater inflater = mActivity.getLayoutInflater();
            mGalleryBackground = (LinearLayout) mActivity.findViewById(R.id.galley_layout);

            final int length = mUrls.size();
            for (int i = 0; i < length; i++) {

                String url = mUrls.get(i);
                ImageView v = (ImageView) inflater
                        .inflate(R.layout.gallery_item, mGalleryBackground, false);
                v.setTag(i);
                v.setOnClickListener(mScreenShotClickListener);
                ImageUtils.downloadDeatilScreenshot(mActivity, url, v);
                mGalleryBackground.addView(v);
            }
        }
    }

    private View.OnClickListener mScreenShotClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.trackEvent(mActivity, Constants.GROUP_8,
                    Constants.DETAIL_CLICK_SNAPSHOT);
            Integer pos = (Integer) v.getTag();
            Intent screenShotIntent = new Intent(mActivity, ScreenshotActivity.class);
            screenShotIntent.putExtra(Constants.EXTRA_PRDUCT_DETAIL, mProductDetail);
            screenShotIntent.putExtra(Constants.EXTRA_SCREENSHOT_ID, pos);
            startActivity(screenShotIntent);
        }
    };

    /*
     * 回收图片资源，避免内存泄露
     */
    private void recycleImage() {

        if (mGalleryBackground == null) {
            return;
        }

        final int childNum = mGalleryBackground.getChildCount();

        for (int i = 0; i < childNum; i++) {
            ImageView v = (ImageView) mGalleryBackground.getChildAt(i);
            BitmapDrawable d = (BitmapDrawable) v.getDrawable();
            v.setImageDrawable(null);
            if (d != null) {
                Bitmap b = d.getBitmap();
                if (b != null) {
                    b.recycle();
                }
                d.setCallback(null);
            }
        }
        mGalleryBackground.removeAllViewsInLayout();
        mGalleryBackground = null;
    }

    /**
     * 初始化产品信息
     */
    private void initProductInfo(ProductDetail product) {

        TextView local =  (TextView) mActivity.findViewById(R.id.label_chinese);
        if (product.isLocal) {
            local.setVisibility(View.VISIBLE);
        } else {
            local.setVisibility(View.GONE);
        }
        TextView clean =  (TextView) mActivity.findViewById(R.id.label_green);
        if (product.isClean) {
            clean.setVisibility(View.VISIBLE);
        } else {
            clean.setVisibility(View.GONE);
        }
        TextView first =  (TextView) mActivity.findViewById(R.id.label_first);
        if (product.isFirst) {
            first.setVisibility(View.VISIBLE);
        } else {
            first.setVisibility(View.GONE);
        }
        TextView star =  (TextView) mActivity.findViewById(R.id.label_verify);
        if (product.isStar) {
            star.setVisibility(View.VISIBLE);
        } else {
            star.setVisibility(View.GONE);
        }

        TextView appVersion = (TextView) mActivity.findViewById(R.id.app_version);
        appVersion.setText(getString(R.string.label_version, product.getVersionName()));

        TextView downloadNum = (TextView) mActivity.findViewById(R.id.app_download);
        downloadNum.setText(getString(R.string.label_downloaded,
                StringUtils.getDownloadInterval(product.getDownloadCount())));

        TextView appSize = (TextView) mActivity.findViewById(R.id.app_size);
        appSize.setText(getString(R.string.label_size,
                StringUtils.formatSize(product.getAppSize())));

        TextView appTime = (TextView) mActivity.findViewById(R.id.app_time);
        appTime.setText(getString(R.string.label_up_time,
                Utils.formatDate(mProductDetail.getUpdateTime())));

        TextView appAuthor = (TextView) mActivity.findViewById(R.id.developer);
        appAuthor.setText(getString(R.string.label_author, mProductDetail.getAuthorName()));
    }

    /**
     * 初始化产品描述信息
     */
    private void initDescriptionView(ProductDetail product) {

        final FrameLayout frame = (FrameLayout) mActivity.findViewById(R.id.app_description);
        ViewTreeObserver vto = frame.getViewTreeObserver();

        mShortDescription = (TextView) mActivity.findViewById(R.id.app_description1);
        mShortDescription.setText(product.getLongDescription());
        mShortDescription.setOnClickListener(this);
        mShortDescription.setVisibility(View.INVISIBLE);
        mLongDescription = (TextView) mActivity.findViewById(R.id.app_description2);
        mLongDescription.setText(product.getLongDescription());
        mLongDescription.setVisibility(View.VISIBLE);
        mLongDescription.setOnClickListener(this);
        mMoreButton = (Button) mActivity.findViewById(R.id.btn_more);
        mMoreButton.setOnClickListener(this);

        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {

                if (isInit) {
                    return true;
                }

                if (measureDescription(mShortDescription, mLongDescription)) {
                    mMoreButton.setVisibility(View.VISIBLE);
                }
                isInit = true;
                return true;
            }
        });
    }

    /**
     * 计算描述信息是否过长
     */
    private boolean measureDescription(TextView shortView, TextView longView) {
        final int shortHeight = shortView.getHeight();
        final int longHeight = longView.getHeight();
        if (longHeight > shortHeight) {
            shortView.setVisibility(View.VISIBLE);
            longView.setVisibility(View.GONE);
            return true;
        }
        shortView.setVisibility(View.GONE);
        longView.setVisibility(View.VISIBLE);
        return false;
    }

    /**
     * 切换【更多】按钮状态
     */
    private void toggleMoreButton() {
        if (mIsShortDescription) {
            mShortDescription.setVisibility(View.GONE);
            mLongDescription.setVisibility(View.VISIBLE);
            mMoreButton.setBackgroundResource(R.drawable.btn_more_collapse);
            mMoreButton.setText(getString(R.string.label_less));
        } else {
            mShortDescription.setVisibility(View.VISIBLE);
            mLongDescription.setVisibility(View.GONE);
            mMoreButton.setBackgroundResource(R.drawable.btn_more_open);
            mMoreButton.setText(getString(R.string.label_more));
        }
        mIsShortDescription = !mIsShortDescription;
    }

    /**
     * 初始化更多应用
     */
    private void initMoreAppView(ArrayList<HashMap<String, Object>> moreApps) {

        if (moreApps == null || moreApps.size() == 0) {
            return;
        }

        // 导入更多应用部分布局
        View root = ((ViewStub) mActivity.findViewById(R.id.stub_import_enjoy)).inflate();

        // 横向滑动布局
        LinearLayout parent = (LinearLayout) root.findViewById(R.id.more_layout);

        for (HashMap<String, Object> item : moreApps) {

            RelativeLayout v = (RelativeLayout) mActivity.getLayoutInflater()
                    .inflate(R.layout.product_maybe_enjoy, parent, false);
            ImageView icon = (ImageView) v.findViewById(R.id.more_app_logo);
            TextView name = (TextView) v.findViewById(R.id.more_app_name);

            String userIconUrl = (String) item.get(Constants.KEY_ICON_URL);
            ImageUtils.download(mActivity, userIconUrl, icon,
                    R.drawable.loading_icon, true, false);
            name.setText((String) item.get(Constants.KEY_PRODUCT_NAME));

            v.setId(MORE_PRODUCT_ID);
            v.setTag(item);
            v.setOnClickListener(this);
            parent.addView(v);
        }
    }

    private RatingBar mMyRating;
    private TextView mRanking;
    private long mLastRatingTime = 0;
    private Handler mHandler = new Handler();

    /**
     * 初始化评级控件
     */
    private void initRatingView() {
        mMyRating = (RatingBar) mActivity.findViewById(R.id.rb_myrating);
        mRanking = (TextView) mActivity.findViewById(R.id.tv_ranking);
        mMyRating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, final float rating, boolean fromUser) {

                if (!mSession.isLogin()) {
                    Utils.gotoLogin(mActivity);
                    return;
                }
                int ranking = (int) rating;
                switch (ranking) {
                    case 1:
                        mRanking.setText(R.string.label_ranking_1);
                        break;
                    case 2:
                        mRanking.setText(R.string.label_ranking_2);
                        break;
                    case 3:
                        mRanking.setText(R.string.label_ranking_3);
                        break;
                    case 4:
                        mRanking.setText(R.string.label_ranking_4);
                        break;
                    case 5:
                        mRanking.setText(R.string.label_ranking_5);
                        break;

                    default:
                        break;
                }

                long currentTime = System.currentTimeMillis();
                if ((mLastRatingTime != 0) && (currentTime - mLastRatingTime > 2000)) {
                    // 防止用户过于频繁提交数据
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            // Bug fixed 2011/9/17
                            if (mProductDetail == null) {
                                return;
                            }

                            Bundle args = new Bundle();
                            args.putInt("rating", (int) rating);
                            getLoaderManager().initLoader(MarketAPI.ACTION_ADD_RATING,
                                    args, ProductDetailFragment.this);
                        }
                    }, 2000);

                    mLastRatingTime = currentTime;
                }
            }
        });
    }


    /**
     * 根据数据，决定是否显示标签页。
     */
    private void showTagsViewIfNeed(Object obj){
        View tagView = mActivity.findViewById(R.id.tag_layout);
        if (obj instanceof List) {
            List<TagsInfo> tagsList = (List<TagsInfo>) obj;
            if(tagsList.size() != 0){
                CategoryTagView tag = (CategoryTagView) mActivity.findViewById(R.id.tv_tagview);
                tag.setTags((List<TagsInfo>) obj);
                tag.setTagsViewOnClickListener(this);
                tagView.setVisibility(View.VISIBLE);
                return ;
            }
        }
        tagView.setVisibility(View.GONE);
    }

    /**
     *  刷新评分
     */
    private void refreshRatingView(int rating) {
        if (rating > 0) {
            mMyRating.setRating(rating);
        }
        // 可以修改评分状态
        mLastRatingTime = 1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.app_description1:
            case R.id.app_description2:
            case R.id.btn_more:
                toggleMoreButton();
                break;
            case MORE_PRODUCT_ID:
                // 前往产品页
                HashMap<String, Object> item = (HashMap<String, Object>) v.getTag();
                String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
                String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
                Intent detailIntent = new Intent(getActivity(), ProductDetailActivity.class);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, name);
                detailIntent.putExtra(Constants.EXTRA_SOURCE_TYPE, Constants.SOURCE_TYPE_GFAN);
                getActivity().startActivity(detailIntent);
        }
    }


    @Override
    public Loader<ApiResponse> onCreateLoader(int id, Bundle args) {

        if (MarketAPI.ACTION_GET_RECOMMEND_BY_APP == id) {

            return MarketAPI.initRecommendByAppLoader(mActivity, mProductDetail.getPid());

        } else if (MarketAPI.ACTION_GET_TAGS_IN_DETAILS == id) {

            return MarketAPI.initTagsByApp(mActivity, mProductDetail.getPid());

        } else if (MarketAPI.ACTION_GET_MYRATING == id) {

            return MarketAPI.initGetRatingLoader(mActivity, mProductDetail.getPid());

        } else if (MarketAPI.ACTION_ADD_RATING == id) {

            return MarketAPI.initAddRatingLoader(mActivity, mProductDetail.getPid(),
                    args.getInt("rating"));
        }

        return null;
    }

    @Override
    public void onLoadFinished(Loader<ApiResponse> loader, ApiResponse data) {

        if (!isVisible()) {
            return;
        }

        if (data.status == ApiResponse.STATUS_LOGIC_ERROR
                || data.status == ApiResponse.STATUS_TIMEOUT_ERROR) {
            // TODO

            return;
        }

        final int actionId = loader.getId();

        switch (actionId) {

            case MarketAPI.ACTION_GET_RECOMMEND_BY_APP: {
                if (mMoreApps == null) {
                    mMoreApps = (ArrayList<HashMap<String, Object>>)
                            ((HashMap<String, Object>) data.result).get(Constants.KEY_PRODUCT_LIST);
                    initMoreAppView(mMoreApps);
                }
                break;
            }

            case MarketAPI.ACTION_GET_TAGS_IN_DETAILS: {

                showTagsViewIfNeed(data.result);
                break;
            }

            case MarketAPI.ACTION_GET_MYRATING: {

                refreshRatingView(Utils.getInt((String) data.result));
                break;
            }

            case MarketAPI.ACTION_ADD_RATING: {

                    // 新增我的评分
                    mRanking.setText(R.string.label_ranking_over);
                break;
            }

        }
    }

    @Override
    public void onLoaderReset(Loader<ApiResponse> loader) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onTagsViewClick(View v, TagsInfo tag) {
        if (tag == null) {
            return;
        }

        Utils.jumpToPage(getActivity(), ThirdFragmentActivity.class, false,
                new String[]{
                        BaseFragmentActivity.KeyStore.KEY_ENTRY,
                        BaseFragmentActivity.KeyStore.KEY_ARG,
                        BaseFragmentActivity.KeyStore.KEY_TITLE
                },
                new Serializable[]{
                        BaseFragmentActivity.KeyStore.TARGET_CATEGORY_TAG_LIST,
                        tag.getTagId(),
                        tag.getTagName()
                });
    }
}
